package com.trigsoft.applist;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

public class StatisticsAct extends Activity implements OnItemClickListener, OnItemLongClickListener
{
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		setContentView(R.layout.statistics);

		ListView lv = (ListView) findViewById(R.id.statisticsList);
		Cursor cursor = DBHelper.queryInCount();
		String[] columns = new String[] {DBHelper.KEY_ICON, DBHelper.KEY_LABEL, DBHelper.KEY_COUNT};
		int[] to = new int[] {R.id.icon, R.id.name, R.id.count};
		SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, R.layout.statistics_item, cursor, columns, to);
		mAdapter.setViewBinder(new StatisticsViewBinder());

		lv.setAdapter(mAdapter);

		lv.setOnItemClickListener(this);
		lv.setOnItemLongClickListener(this);

		findViewById(R.id.android_stats).setOnClickListener(new OnClickListener() {

			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				Intent intent = new Intent(Intent.ACTION_MAIN);
				intent.setComponent(new ComponentName("com.android.settings", "com.android.settings.UsageStats"));
				startActivity(intent);
			}

		});
	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
	{
		// TODO Auto-generated method stub
		Cursor c = (Cursor) arg0.getItemAtPosition(arg2);
		String n = c.getString(c.getColumnIndex(DBHelper.KEY_NAME));
		if (n == null)
		{
			Toast.makeText(this, "此程序没有应用界面,无法启动，请查看是用说明。", Toast.LENGTH_SHORT).show();
			return;
		}
		String p = c.getString(c.getColumnIndex(DBHelper.KEY_PKG));
		try
		{
			startActivity(App.setActivity(p, n));
		} catch (ActivityNotFoundException e)
		{
			DBHelper.deleteAppEntry(p);
		}
		finish();
	}

	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
	{
		// TODO Auto-generated method stub
		new ContextDialog(this, arg0, arg2).show();
		return true;
	}

}
